package com.hr.dao.impl;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.hr.dao.DepartmentDao;
import com.hr.pojo.Department;
import com.hr.utils.C3P0Utils;

public class DepartmentDaoImpl implements DepartmentDao {
	private QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
	@Override
	public List findAllDepartments() {
		String sql ="select * from hr_department";
		List<Department> list = null;
		try {
			 list = queryRunner.query(sql, new BeanListHandler<Department>(Department.class));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return list;
	}
	@Override
	public void saveDepartment(Department department) {
		
		String sql ="insert into hr_department(name) values(?)";
		Object[] params = new Object[]{department.getName()};
		try {
			queryRunner.update(sql, params);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	@Override
	public Department findDepartmentById(String id) {
		String sql ="select * from hr_department where id = ? ";
		Department department = null;
		try {
			department = queryRunner.query(sql, new BeanHandler<>(Department.class), id);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return department;
	}
	@Override
	public void updateDepartment(Department department) {
		String sql ="update hr_department set name = ? where id = ?";
		Object[] params = new Object[]{department.getName(),department.getId()};
		try {
			queryRunner.update(sql, params);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}
	@Override
	public void deleteDepartment(String id) {
		String sql ="delete from hr_department where id = ? ";
		try {
			queryRunner.update(sql, id);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}